package com.producer.controller.singloton;

import com.producer.entity.Mgr01;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * @Description
 * @Author youxin
 * @Version V1.0.0
 * @Since 1.0
 * @Date 2021/6/25
 */
public class TestSinglotonController {
    @Autowired
    private RedisTemplate redisTemplate;
    public static void main(String[] args) {
       Mgr01.getINSTANCE();
    }
    /**
     * 加锁
     *
     * @param key    redis key
     * @param expire 过期时间，单位秒
     * @param retry  重试时间，单位秒
     * @return true:加锁成功，false，加锁失败
     */
    public static boolean lock(RedisTemplate redisTemplate, String key, int expire, int retry, TimeUnit timeUnit) {
        long currentTimeMillis = System.currentTimeMillis();
        long value = currentTimeMillis + expire * 1000;
        long end = currentTimeMillis+ retry * 1000;

        while ( System.currentTimeMillis() <= end) {
            boolean status = false;
            try {
                status = redisTemplate.opsForValue().setIfAbsent(key, String.valueOf(value), expire, timeUnit);
            } catch (Exception e) {
                break;
            }
            if (status) {
                return true;
            }
            //重试
            if (!status && retry>0){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }


        }

        return false;
    }
}
